/**
 * 数据验证工具
 */

import type { EvaluationItem, ExportConfig } from '@/types/ProofMapper';

export class ValidationError extends Error {
  constructor(message: string, public field?: string) {
    super(message);
    this.name = 'ValidationError';
  }
}

/**
 * 验证文件类型和大小
 */
export const validateFile = (file: File): void => {
  // 验证文件类型
  if (file.type !== 'application/pdf') {
    throw new ValidationError('请上传PDF格式的文件', 'fileType');
  }

  // 验证文件大小 (限制为50MB)
  const maxSize = 50 * 1024 * 1024; // 50MB
  if (file.size > maxSize) {
    throw new ValidationError('文件大小不能超过50MB', 'fileSize');
  }

  // 验证文件名
  if (!file.name || file.name.trim().length === 0) {
    throw new ValidationError('文件名不能为空', 'fileName');
  }
};

/**
 * 验证评估项数据
 */
export const validateEvaluationItem = (item: Partial<EvaluationItem>): void => {
  if (!item.module || item.module.trim().length === 0) {
    throw new ValidationError('评估模块不能为空', 'module');
  }

  if (!item.checkpoint || item.checkpoint.trim().length === 0) {
    throw new ValidationError('查验点不能为空', 'checkpoint');
  }

  if (!item.materials || item.materials.length === 0) {
    throw new ValidationError('所需证明材料不能为空', 'materials');
  }

  // 验证长度限制
  if (item.module.length > 100) {
    throw new ValidationError('评估模块名称不能超过100个字符', 'module');
  }

  if (item.checkpoint.length > 200) {
    throw new ValidationError('查验点名称不能超过200个字符', 'checkpoint');
  }

  if (item.materials.length > 10) {
    throw new ValidationError('所需证明材料数量不能超过10个', 'materials');
  }

  if (item.notes && item.notes.length > 500) {
    throw new ValidationError('备注不能超过500个字符', 'notes');
  }
};

/**
 * 验证导出配置
 */
export const validateExportConfig = (config: ExportConfig): void => {
  const validFormats = ['word', 'excel'];
  if (!validFormats.includes(config.format)) {
    throw new ValidationError('无效的导出格式', 'format');
  }

  if (typeof config.include_notes !== 'boolean') {
    throw new ValidationError('include_notes必须是布尔值', 'include_notes');
  }

  if (typeof config.include_summary !== 'boolean') {
    throw new ValidationError('include_summary必须是布尔值', 'include_summary');
  }

  if (typeof config.selected_items_only !== 'boolean') {
    throw new ValidationError('selected_items_only必须是布尔值', 'selected_items_only');
  }
};

/**
 * 验证AI指令
 */
export const validateAICommand = (command: string): void => {
  if (!command || command.trim().length === 0) {
    throw new ValidationError('AI指令不能为空', 'command');
  }

  if (command.length > 500) {
    throw new ValidationError('AI指令不能超过500个字符', 'command');
  }

  // 检查是否包含敏感内容或无效指令
  const forbiddenPatterns = [
    /删除所有/i,
    /清空/i,
    /格式化/i
  ];

  for (const pattern of forbiddenPatterns) {
    if (pattern.test(command)) {
      throw new ValidationError('指令包含不安全的操作', 'command');
    }
  }
};

/**
 * 批量验证评估项
 */
export const validateEvaluationItems = (items: EvaluationItem[]): ValidationError[] => {
  const errors: ValidationError[] = [];

  items.forEach((item, index) => {
    try {
      validateEvaluationItem(item);
    } catch (error) {
      if (error instanceof ValidationError) {
        errors.push(new ValidationError(
          `第${index + 1}项：${error.message}`,
          `item[${index}].${error.field}`
        ));
      }
    }
  });

  return errors;
};

/**
 * 检查重复项
 */
export const findDuplicateItems = (items: EvaluationItem[]): EvaluationItem[][] => {
  const duplicates: EvaluationItem[][] = [];
  const seen = new Map<string, EvaluationItem[]>();

  items.forEach(item => {
    const key = `${item.module}-${item.checkpoint}`;
    if (!seen.has(key)) {
      seen.set(key, []);
    }
    seen.get(key)!.push(item);
  });

  seen.forEach(group => {
    if (group.length > 1) {
      duplicates.push(group);
    }
  });

  return duplicates;
};

/**
 * 数据清理工具
 */
export const sanitizeEvaluationItem = (item: Partial<EvaluationItem>): Partial<EvaluationItem> => {
  return {
    ...item,
    module: item.module?.trim(),
    checkpoint: item.checkpoint?.trim(),
    materials: item.materials?.map(material => material.trim()),
    notes: item.notes?.trim() || ''
  };
};

/**
 * 格式化文件大小
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

/**
 * 生成唯一ID
 */
export const generateId = (prefix: string = ''): string => {
  const timestamp = Date.now().toString(36);
  const randomStr = Math.random().toString(36).substring(2, 8);
  return `${prefix}${prefix ? '-' : ''}${timestamp}-${randomStr}`;
};
